package com.coisini.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coisini.constant.MessageConstant;
import com.coisini.dto.UserLoginDTO;
import com.coisini.entity.User;
import com.coisini.exception.LoginFailedException;
import com.coisini.mapper.UserMapper;
import com.coisini.properties.WeChatProperties;
import com.coisini.service.UserService;
import com.coisini.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.调用微信提供的APi获得openid
        String openid = getOpenId(userLoginDTO.getCode());
        //2.判断openid
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.根据openid调用mapper接口进行查询
        User user = userMapper.getByOpenid(openid);
        //4.判断返回的用户是否是新用户，即数据表中是否存在
        if (user == null){
            log.info("当前用户为新用户");
            //5.不存在，将其添加到表中
           user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
           userMapper.insert(user);
        }
        //6.存在，返回用户
        return  user;
    }

    /**
     * 调用微信提供的APi获得openid
     * 请求返回的数据是json格式的字符串，需要将其转为json格式，在将key：openid对应的值取出
     * @param code
     * @return
     */
    private String getOpenId(String code){
        Map<String, String> map=new HashMap<>();
        //将请求参数添加到集合中
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        //返回的 数据是员工json格式的字符串
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
